<template>
  <div class="app-container">
    <div class="card-header" style="border: solid 1px #eaeefb;">
          <span>WebSocket 消息中心（用户ID：{{ currentUserId }}）</span>
          <el-tag :type="connectionStatus ? 'success' : 'danger'">
            {{ connectionStatus ? "已连接" : "已断开" }}
          </el-tag>
          <el-tag  v-if="!connectionStatus" @click="initWebSocket">
           重新连接
          </el-tag>
        </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="帐号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择帐号状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_statue"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="最后登录IP" prop="loginIp">
        <el-input
          v-model="queryParams.loginIp"
          placeholder="请输入最后登录IP"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后登录时间" prop="loginDate">
        <el-date-picker clearable
          v-model="queryParams.loginDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择最后登录时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['user:notification:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['user:notification:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user:notification:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['user:notification:export']"
        >导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-bell"
          size="mini"
          @click="handleNotifyAnnounce"
          v-hasPermi="['user:notification:export']"
        >发布公告给所有用户</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="notificationList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户账号" align="center" prop="userName" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="帐号状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_statue" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" align="center" prop="loginIp" />
      <el-table-column label="最后登录时间" align="center" prop="loginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
      size="mini"
      type="text"
      icon="el-icon-message"
      @click="handleNotify(scope.row)"
      v-hasPermi="['system:user:list']"
    >通知</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['user:notification:edit']"
          >修改</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['user:notification:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <!-- <el-form-item label="帐号状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择帐号状态">
            <el-option
              v-for="dict in dict.type.sys_user_statue"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入最后登录IP" />
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker clearable
            v-model="form.loginDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 消息发送对话框 -->
<el-dialog title="发送通知" :visible.sync="notifyDialogVisible" width="500px">
  <el-form :model="messageForm" label-width="80px">
    <el-form-item label="接收用户">
      <el-input v-model="messageForm.toUserName" disabled />
    </el-form-item>
    <el-form-item label="消息类型" prop="type">
      <el-select v-model="messageForm.type"   placeholder="普通">
        <el-option label="普通" value="common"></el-option>
        <el-option label="重要(警告等)" value="urgent"></el-option>
        <el-option label="其他" value="other"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="消息内容" prop="content">
      <editor v-model="messageForm.content" :min-height="192"/>
      <!-- <el-input
        v-model="messageForm.content"
        type="textarea"
        :rows="4"
        placeholder="请输入通知内容"
        show-word-limit
        maxlength="500"
      /> -->
    </el-form-item>
  </el-form>
  <div slot="footer">
    <el-button @click="notifyDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="sendMessage">发 送</el-button>
  </div>
</el-dialog>
<!-- 公告对话框 -->
<el-dialog title="发送公告" :visible.sync="notifyDialogVisibleAnnounce" width="500px">
  <el-form :model="messageForm" label-width="80px">
    <el-form-item label="接收用户">
      所有人
    </el-form-item>
    <el-form-item label="消息类型" prop="type">
     公告
    </el-form-item>
    <el-form-item label="消息内容" prop="content">
      <editor v-model="messageForm.content" :min-height="192"/>
      <!-- <el-input
        v-model="messageForm.content"
        type="textarea"
        :rows="4"
        placeholder="请输入通知内容"
        show-word-limit
        maxlength="500"
      /> -->
    </el-form-item>
  </el-form>
  <div slot="footer">
    <el-button @click="notifyDialogVisibleAnnounce = false">取 消</el-button>
    <el-button type="primary" @click="sendBroadcastMessage">发 送</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import { listNotification, getNotification, delNotification, addNotification, updateNotification,sendPrivateMessage,sendBroadcastMessage,getOnlineUsers} from "@/api/user/notification";
import { getToken } from '@/utils/auth'
import { Message as ElMessage } from 'element-ui'

export default {
  name: "Notification",
  dicts: ['sys_user_statue', 'sys_user_sex'],
  data() {
    return {
      //公告对话框
      notifyDialogVisibleAnnounce:false,
       // 新增对话框控制
    notifyDialogVisible: false,
      currentUserId: '',
      socket: null,
      connectionStatus: false,
      messages: [],
      messageForm: {
        type:"common",
        toUserId: '',
        toUserName: '', // 新增接收用户显示
        content: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户通知表格数据
      notificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        nickName: null,
        phonenumber: null,
        status: null,
        loginIp: null,
        loginDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户账号不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initWebSocket()

  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close()
    }
  },
  methods: {
    handleNotifyAnnounce() {
    this.messageForm = {
      content: ''
    }
    this.notifyDialogVisibleAnnounce = true
  },
    handleNotify(row) {
    this.messageForm = {
      toUserId: row.userId,
      toUserName: `${row.nickName} (${row.userName})`,
      content: ''
    }
    this.notifyDialogVisible = true
  },

    initWebSocket() {
      const token = getToken()
      if (!token) {
        ElMessage.error('未获取到登录令牌，请先登录')
        return
      }

      try {
        const wsUrl = `wss://xit-edu.cn/ws/endpoint/${encodeURIComponent(token)}`
        this.socket = new WebSocket(wsUrl)

        // 连接成功
        this.socket.onopen = () => {
          this.connectionStatus = true
          ElMessage.success('WebSocket 连接成功')
          // 从 localStorage 获取用户信息（根据实际业务调整）
          const userInfo = JSON.parse(localStorage.getItem('userInfo'))
          this.currentUserId = userInfo ? userInfo.userId : ''
        }

        // 接收消息
        this.socket.onmessage = (event) => {
          const message = JSON.parse(event.data)
          console.log('Received message:', event.data)
          // const message=event.data
          this.messages.push({
            ...message,
            direction: 'received',
            timestamp: new Date().toLocaleTimeString()
          })
        }

        // 连接关闭
        this.socket.onclose = () => {
          this.connectionStatus = false
          ElMessage.warning('WebSocket 连接已关闭')
        }

        // 错误处理
        this.socket.onerror = (error) => {
          console.error('WebSocket 错误:', error)
          ElMessage.error('连接发生错误')
        }

      } catch (e) {
        console.error('WebSocket 初始化失败:', e)
        ElMessage.error('连接初始化失败')
      }
    },

    // 优化后的发送方法
  sendMessage() {
    if (!this.validateMessage()) return

    const payload = {
      type: this.messageForm.type == null?'common':this.messageForm.type, // 消息类型区分
      fromUserId: this.currentUserId,
      toUserId: this.messageForm.toUserId,
      content: this.messageForm.content,
      timestamp: new Date().getTime()
    }
    sendPrivateMessage(payload)
      .then(() => {
        this.$message.success('通知发送成功')
        this.notifyDialogVisible = false
        // 添加到本地消息记录
        this.messages.push({
          ...payload,
          direction: 'sent',
          timestamp: new Date().toLocaleString()
        })
      })
      .catch(error => {
        this.$message.error('通知发送失败')
      })
    // try {
    //   this.socket.send(JSON.stringify(payload))
    //   this.$message.success('通知发送成功')
    //   this.notifyDialogVisible = false
    //   // 添加到本地消息记录
    //   this.messages.push({
    //     ...payload,
    //     direction: 'sent',
    //     timestamp: new Date().toLocaleString()
    //   })
    // } catch (e) {
    //   this.$message.error('通知发送失败')
    //   console.error('发送失败:', e)
    // }
  },
  sendBroadcastMessage() {
    if (!this.validateMessage()) return
    const payload = {
      type: "announce", // 消息类型区分
      fromUserId: this.currentUserId,
      toUserId: this.messageForm.toUserId,
      content: this.messageForm.content,
      timestamp: new Date().getTime()
    }
    sendBroadcastMessage(payload)
      .then(() => {
        this.$message.success('通知发送成功')
        this.notifyDialogVisible = false
        // 添加到本地消息记录
        this.messages.push({
          ...payload,
          direction: 'sent',
          timestamp: new Date().toLocaleString()
        })
      })
      .catch(error => {
        this.$message.error('通知发送失败')
      })
  },
  validateMessage() {
    if (!this.messageForm.content.trim()) {
      this.$message.warning('请输入通知内容')
      return false
    }
    if (this.messageForm.content.length > 500) {
      this.$message.warning('内容长度不能超过500字符')
      return false
    }
    return true
  },
    /** 查询用户通知列表 */
    getList() {
      this.loading = true;
      listNotification(this.queryParams).then(response => {
        this.notificationList = response.rows;
        this.notificationList = this.notificationList.filter(item => item.userType != "00");
        this.total = response.total;
        this.loading = false;
        getOnlineUsers().then(response => {
      this.notificationList.forEach(item => {
        // console.log(item)
    if (response.data.includes(item.userId)) {
        item.status = "2";
    }
});
    })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        status: null,
        delFlag: null,
        loginIp: null,
        loginDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户通知";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getNotification(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户通知";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateNotification(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotification(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户通知编号为"' + userIds + '"的数据项？').then(function() {
        return delNotification(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/notification/export', {
        ...this.queryParams
      }, `notification_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 样式部分与 Vue 3 版本完全一致，无需修改 */
.message-container {
  height: 400px;
  margin-bottom: 20px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
}

.message-item {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 80%;
}

.message-item.received {
  background-color: #f5f7fa;
  margin-right: auto;
}

.message-item.sent {
  background-color: #409eff;
  color: white;
  margin-left: auto;
}

.message-meta {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-meta .time {
  margin-left: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

